<template>
  <el-header class="header" v-reveal="{ delay: 40, distance: 10 }">
    <div class="container">
      <div class="header-content">
        <div class="logo">
          <img 
            src="/src/assets/images/logo.svg" 
            alt="KBB Logo" 
            class="logo-image"
            @error="handleImageError"
          />
          <h1>KBB</h1>
        </div>
        
        <el-menu
          :default-active="activeIndex"
          class="nav-menu"
          mode="horizontal"
          router
          @select="handleSelect"
        >
          <el-menu-item index="/">首页</el-menu-item>
          <el-menu-item index="/announcements">公告</el-menu-item>
          <el-menu-item index="/banlist">封禁名单</el-menu-item>
          <el-menu-item index="/commands">指令</el-menu-item>
          <el-menu-item index="/donation">捐赠</el-menu-item>
          <el-menu-item index="/donor-thanks">感谢名单</el-menu-item>
        </el-menu>

        <div class="header-actions">
          <el-button type="primary" @click="joinServer" :disabled="!serverStatus.online">
            加入服务器
          </el-button>
          
          <!-- 用户信息区域 -->
          <div class="user-section">
            <template v-if="userStore.isLoggedIn">
              <el-dropdown @command="handleUserCommand">
                <span class="user-info">
                  <img 
                    v-if="userStore.userInfo?.avatar" 
                    :src="userStore.userInfo.avatar" 
                    :alt="userStore.username + '的头像'"
                    class="user-avatar"
                    @error="handleAvatarError"
                  />
                  <el-icon v-else class="user-icon"><User /></el-icon>
                  {{ userStore.username }}
                  <el-icon class="arrow-icon"><ArrowDown /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="profile">个人中心</el-dropdown-item>
                    <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
            <template v-else>
              <span class="login-status">未登录</span>
              <el-button type="success" size="small" @click="goToLogin">
                登录
              </el-button>
              <el-button type="primary" size="small" @click="goToRegister" style="margin-left: 8px;">
                注册
              </el-button>
            </template>
          </div>
        </div>
      </div>
    </div>
  </el-header>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, ArrowDown } from '@element-plus/icons-vue'
import { getServerStatus } from '../api/serverApi'
import { useUserStore } from '../stores/user'

export default {
  name: 'Header',
  components: {
    User,
    ArrowDown
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const userStore = useUserStore()
    const serverStatus = ref({
      online: false,
      playerCount: 0,
      maxPlayers: 50
    })

    const activeIndex = computed(() => route.path)

    const handleSelect = (key) => {
      console.log('导航到:', key)
    }

    const joinServer = () => {
      if (serverStatus.value.online) {
        // 复制服务器IP到剪贴板
        navigator.clipboard.writeText('mc.kbblet.cn:25565')
        ElMessage.success('服务器IP已复制到剪贴板！')
      }
    }
    
    const goToLogin = () => {
      router.push('/login')
    }
    
    const goToRegister = () => {
      router.push('/register')
    }
    
    const handleUserCommand = async (command) => {
      if (command === 'logout') {
        await userStore.logout()
        ElMessage.success('已退出登录')
        // 退出登录后跳转到首页
        router.push('/')
      } else if (command === 'profile') {
        // 跳转到个人中心页面
        router.push('/profile')
      }
    }

    const fetchServerStatus = async () => {
      try {
        const response = await getServerStatus()
        if (response.success) {
          serverStatus.value = response.data
        } else {
          console.error('获取服务器状态失败:', response.message)
          // 提供默认值
          serverStatus.value = {
            online: false,
            playerCount: 0,
            maxPlayers: 50,
            ping: 0,
            version: '1.21.4'
          }
        }
      } catch (error) {
        console.error('获取服务器状态失败:', error)
        // 提供默认值
        serverStatus.value = {
          online: false,
          playerCount: 0,
          maxPlayers: 50,
          ping: 0,
          version: '1.21.4'
        }
      }
    }
    
    const handleImageError = (event) => {
      // 图片加载失败时使用默认图标
      event.target.style.display = 'none'
      console.warn('Logo图片加载失败，已隐藏')
    }
    
    const handleAvatarError = (event) => {
      // 头像加载失败时隐藏图片，显示默认图标
      event.target.style.display = 'none'
      console.warn('用户头像加载失败，使用默认图标')
    }

    onMounted(() => {
      fetchServerStatus()
      // 每30秒刷新一次服务器状态
      setInterval(fetchServerStatus, 30000)
    })

    return {
      activeIndex,
      serverStatus,
      userStore,
      handleSelect,
      joinServer,
      goToLogin,
      goToRegister,
      handleUserCommand,
      handleImageError,
      handleAvatarError
    }
  }
}
</script>

<style scoped>
.header {
  height: 90px;
  padding: 15px 20px;
  
  backdrop-filter: blur(12px);
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
  position: sticky;
  border-radius: 50px;
  margin: 10px 30px;
  top: 10px;
  z-index: 1000;
  border: 1px solid #e5e7eb;
  transition: all 0.3s ease;
}

.header:hover {
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100%;
  position: relative;
}

.logo {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.logo:hover {
  transform: scale(1.05);
}

.logo-image {
  width: 40px;
  height: 40px;
  border-radius: 12px;
  object-fit: contain;
}

.logo h1 {
  color: #1f2937;
  font-size: 1.5rem;
  font-weight: bold;
  margin: 0;
}

.nav-menu {
  flex: 1;
  font-size: 1rem;
  justify-content: center;
  border-bottom: none;
  background: transparent;
}

.nav-menu .el-menu-item {
  font-weight: 500;
  font-size: 1.2rem;
  color: #4b5563;
  transition: color 0.3s ease;
  border-bottom: 2px solid transparent;
}

.nav-menu .el-menu-item:hover {
  color: #4CAF50;
  background: transparent;
}

.nav-menu .el-menu-item.is-active {
  color: #4CAF50;
  border-bottom-color: #4CAF50;
  background: transparent;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 20px;
  min-width: 280px;
  justify-content: flex-end;
}

.user-section {
  display: flex;
  align-items: center;
  gap: 15px;
  min-width: 150px;
  justify-content: flex-end;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 16px;
  border-radius: 25px;
  background: rgba(76, 175, 80, 0.1);
  color: #4CAF50;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
  min-width: 120px;
  justify-content: center;
}

.user-info:hover {
  background: rgba(76, 175, 80, 0.15);
  transform: translateY(-1px);
}

.user-icon {
  font-size: 16px;
}

.user-avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #4CAF50;
  transition: all 0.3s ease;
}

.user-avatar:hover {
  transform: scale(1.1);
  box-shadow: 0 2px 8px rgba(76, 175, 80, 0.3);
}

.arrow-icon {
  font-size: 12px;
  transition: transform 0.3s ease;
}

.login-status {
  color: #6b7280;
  font-size: 14px;
  font-weight: 500;
}

.header-actions .el-button {
  border-radius: 50px;
  font-weight: 600;
  padding: 12px 24px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 6px -1px rgba(76, 175, 80, 0.2);
}

.header-actions .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 15px -3px rgba(76, 175, 80, 0.3);
}

@media (max-width: 1024px) {
  .header {
    margin: 10px 20px;
    height: auto;
    padding: 20px;
  }
  
  .header-content {
    flex-wrap: wrap;
    gap: 20px;
  }
  
  .nav-menu {
    order: 3;
    width: 100%;
    justify-content: center;
  }
  
  .header-actions {
    min-width: auto;
    flex-wrap: wrap;
    gap: 15px;
  }
  
  .user-section {
    min-width: auto;
  }
}

@media (max-width: 768px) {
  .header {
    margin: 10px 15px;
    height: auto;
    padding: 20px 15px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 20px;
  }
  
  .logo h1 {
    font-size: 1.25rem;
  }
  
  .header-actions {
    width: 100%;
    justify-content: center;
    flex-direction: column;
    gap: 15px;
  }
  
  .user-section {
    width: 100%;
    justify-content: center;
  }
  
  .user-info {
    min-width: 140px;
  }
}

@media (max-width: 480px) {
  .header {
    margin: 10px 10px;
  }
  
  .nav-menu {
    font-size: 0.9rem;
  }
  
  .logo-image {
    width: 32px;
    height: 32px;
  }
  
  .logo h1 {
    font-size: 1.1rem;
  }
}
</style>